import { getToken, removeToken, setToken } from "../utils/auth"

const baseUrl = 'http://localhost:8080'

export const get = (uri: string) => {
    wx.showLoading({
        title: '加载中'
    })

    return new Promise<any>((resolve, reject) => {
        wx.request({
            url: baseUrl + uri,
            method: 'GET',
            success: (res) => {
                if (res.statusCode === 401) {
                    removeToken()
                    const currentPages = getCurrentPages()
                    const currentRoute = currentPages[currentPages.length - 1].route
                    // console.log(currentPages[currentPages.length-1].route);
                    if (currentRoute !== 'pages/login/index') {
                        wx.navigateTo({
                            url: `/pages/login/index?redirect=${currentRoute}`
                        })
                    }
                    wx.showToast({
                        title: '请先登录',
                        icon: 'error'
                    })
                }
                //handleHttpError(res,reject)
                resolve(res.data)
            },
            fail: reject,
            complete: () => {
                wx.hideLoading()
            }
        })
    })
}

export const post = (uri: String, data: Object) => {
    wx.showLoading({
        title: '加载中'
    })
    return new Promise<any>((resolve, reject) => {
        wx.request({
            url: baseUrl + uri,
            method: 'POST',
            data,
            success: (res) => {
                //handleHttpError(res,reject)
                if (res.statusCode === 401) {
                    removeToken()
                    const currentPages = getCurrentPages()
                    const currentRoute = currentPages[currentPages.length - 1].route
                    // console.log(currentPages[currentPages.length-1].route);
                    if (currentRoute !== 'pages/login/index') {
                        wx.navigateTo({
                            url: `/pages/login/index?redirect=${currentRoute}`
                        })
                    }
                    wx.showToast({
                        title: '请先登录',
                        icon: 'error'
                    })
                }
                _hdanleToken(res.header)
                // console.log(res.header['Authorization']);
                resolve(res.data)
            },
            fail: reject,
            complete: () => {
                wx.hideLoading()
            }
        })
    })
}

/*const handleHttpError = (response,reject) => {
    if(response.statusCode!==200){
        reject('请求异常')
    }
}*/

const _hdanleToken = (header: any) => {
    const token = header['Authorization']
    if(token&&getToken()!==token){
        setToken(token)
        wx.navigateBack()
    }
}